<?php
	include '../include/functions.php';
	include '../include/update.php';
	//Connect To Database
	dbConnect();
	//updateRecords(); /* This is now done in ../include/Winners.php as games end.
	updateUScores();
	updateURanks();
?>
<html>
  <HEAD>
    <TITLE>JoshHughes.com NFL Football Pool Site</TITLE>
    <link rel="stylesheet" href="css/NFLPool.css" type="text/css">
</head>
<body leftmargin="0" topmargin="0" bottommargin="0" rightmargin="0" marginwidth="0" marginheight="0">
<?
	
	
	//check to see if a Weeknum value was passed, if not, set WeekNum to Weeknum.
	if (($Weeknum == NULL) || ($Weeknum == "")) {
		$Weeknum = getWeek();
	}
	//check to make sure $Weeknum > 1 AND $Weeknum < 21
	$Weeknum = checkWeekBounds($Weeknum);
	if ($Weeknum > 1) {
		$LastWeek = $Weeknum-1;
	}
	else {
		$LastWeek = $Weeknum;
	}
	updateSurvivors($LastWeek);
	
	echo "LastWeek = $LastWeek <br/>";
	//Write SQL Query to extract specified data
	$SQL = "SELECT * FROM NFLSchedule Where (WEEK=".$LastWeek.") AND (Winner != ' ')";
	//Open Record Set using SQL Query
	$result = mysql_query($SQL) or die("Cannot query the database.<br>" . mysql_error());
	if($myrow = mysql_fetch_array($result))
	{
		//Select user information from the Users table, if the user wants to be reminded
		if($LastWeek > 17)
		{
			$SQL = "SELECT ID, username, email FROM NFLUsers WHERE TuesdayEmail = 1 AND PlayOffs = 1 ORDER BY username";
		}
		else
		{
			$SQL = "SELECT ID, username, email FROM NFLUsers WHERE TuesdayEmail = 1";
		}
		//Open Record Set using SQL Query
		$Emailresult = mysql_query($SQL) or die("Cannot query the database.<br>" . mysql_error());
		//set up some email varibables
		$adminmail = "<Football@joshhughes.com>";
		$MailFrom = "From: Football@joshhughes.com";
		$MailSubject = "Football Pool Results For Week ".$LastWeek;
		$MailBody = "Here are the results from the http://football.joshhughes.com Football pool for week ". $LastWeek .":\n";
		$HTMLMailBody = "Here are the results from the <a href=\"http://football.joshhughes.com\">http://football.joshhughes.com</a> Football pool for <B>Week ". $LastWeek ."</B>:<BR><BR>";
		do{
		    if ($Emailrow["email"] != "") {   //add user's email to the list.
			$adminmail .= ", ".$Emailrow["username"]." <".$Emailrow["email"].">";
		    }//end if ($Emailrow["email"] != "")
		}while($Emailrow = mysql_fetch_array($Emailresult));
		
		$HTMLMailBody .=  "<table bgcolor=\"#FFFFFF\" border=\"1\" callpadding=\"5\" cellspacing=\"0\" width=\"100%\" align=\"center\">";
			
			$query="SELECT * FROM NFLSchedule Where (WEEK=".$LastWeek.") ORDER BY GameNum";
			$doQuery=mysql_query($query);
			$numrows=mysql_num_rows($doQuery);
			$num = 1;
			if($numrows > 0)
			{
				while($results=mysql_fetch_array($doQuery))
				{
					//Fill Arrays With Data
					$homeTeams[$num]=$results['Home'];
					$awayTeams[$num]=$results['Away'];
					$winners[$num]=$results['Winner'];
					$num++;
				}
				
				//Print Away Line
				$HTMLMailBody .=  "<tr bgcolor=\"#FFFFFF\"><td><b>Away</b></td>";
				foreach($awayTeams as $team)
				{
				  $HTMLMailBody .=  "<td width=\"5\" align=\"center\"><img src=\"http://football.joshhughes.com/images/small/".$team.".gif\"></td>";
				}
				$HTMLMailBody .=  "<td rowspan=\"3\" valign=\"center\" align=\"center\"><b>Week<br/>$LastWeek<br/>Score</b></td></tr>";
				
				//Print @ Line
				$HTMLMailBody .=  "<tr bgcolor=\"#FFFFFF\"><td>&nbsp;</td>";
				foreach($homeTeams as $team)
				{
				  $HTMLMailBody .=  "<td width=\"5\" align=\"center\">@</td>";
				}
				$HTMLMailBody .=  "</tr>";
				
				//Print Home Line
				$HTMLMailBody .=  "<tr bgcolor=\"#FFFFFF\" bordercolor=\"#172693\"><td><b>Home</b></td>";
				foreach($homeTeams as $team)
				{
				  $HTMLMailBody .=  "<td width=\"5\" align=\"center\"><img src=\"http://football.joshhughes.com/images/small/".$team.".gif\"></td>";
				}
				$HTMLMailBody .=  "</tr>";
				
				$cols = $numrows + 2;
				$HTMLMailBody .=  "<tr height=\"1\" bgcolor=\"#FFFFFF\"><td colspan=\"$cols\" bgcolor=\"#FF0000\"><span style=\"font-size: 8px;\"&nbsp;</td></tr>";
				
				//Print Winner Line
				$HTMLMailBody .=  "<tr bgcolor=\"#FFFFFF\"><td><span style=\"color: rgb(255, 0, 0); font-weight: bold;\">Winner</span></td>";
				$MailBody .=  "The game winners were:\n";
				foreach($winners as $team)
				{
					if($team != "")
					{
						$HTMLMailBody .=  "<td width=\"5\" align=\"center\"><img src=\"http://football.joshhughes.com/images/small/".$team.".gif\"></td>";
						$MailBody .=  "\t$team\n";
					}
					else
					{
						$HTMLMailBody .=  "<td width=\"5\" align=\"center\">&nbsp;</td>";
					}
				}
				$HTMLMailBody .=  "<td>&nbsp;</td></tr>";
				$HTMLMailBody .=  "<tr height=\"1\" bgcolor=\"#FFFFFF\"><td colspan=\"$cols\" bgcolor=\"#FF0000\><span style=\"font-size: 8px;\"&nbsp;</td></tr>\n";
				//Print Rows For User & Picks
				
				//Get Data From Users Who Picked
				$UserPickedSQL = "SELECT NFLPicks.*, NFLUsers.username, NFLUsers.ID FROM NFLPicks, NFLUsers WHERE ((NFLPicks.Week = ".$LastWeek.") AND (NFLPicks.UserID = NFLUsers.ID))  ORDER BY NFLPicks.UserID ASC";
				$UserPickedresult = mysql_query($UserPickedSQL) or die("Cannot query the database.<br>" . mysql_error());
				$row = 0;
				do{
				
					if ($myrow["UserID"] != NULL)
					{
						//increment row for the row color
						$row++;
						$HTMLMailBody .=  "<tr bgcolor=\"".getrowColor($row)."\">";
						$HTMLMailBody .=  "<td><a href=\"members.php?ID=".$myrow["UserID"]."\" class=\"permLink\">".$myrow["username"]."</a></td>\n";
						$MailBody .=  "\n\n".$myrow["username"]." picked:\n";
						$weekScore = 0;
						for($j = 1; $j <= $numrows; $j++)
						{
							$pick = $myrow["Game".$j];
							$MailBody .=  "\t\t$pick\n";
			
							if($winners[$j])
							{
								if($pick == $winners[$j])
								{
									$HTMLMailBody .=  "<td width=\"5\" align=\"center\"><img src=\"http://football.joshhughes.com/images/small/".$pick.".gif\" /></td>\n";
									$weekScore++;
								}
								else
								{
									$HTMLMailBody .=  "<td width=\"5\" align=\"center\"><img src=\"http://football.joshhughes.com/images/red-x.gif\" /></td>\n";
								}
							}
							else
							{
								$HTMLMailBody .=  "<td width=\"5\" align=\"center\">&nbsp;</td>\n";
							}
							
						}
						$HTMLMailBody .=  "<td align=\"center\"><span style=\"color: rgb(255, 0, 0); font-weight: bold; font-size: 16px;\">$weekScore</span></td></tr>\n";
						$MailBody .=  "\t".$myrow["username"]."'s week $LastWeek score: $weekScore out of $numrows.\n";
					}
					
				}while($myrow = mysql_fetch_array($UserPickedresult));
				
			}
			else
			{
				print '<tr bgcolor=\"#FFFFFF\"><td colspan=\"$cols\" align=\"center\">No Games Set for This Week Yet.</td></tr>';
			}
			//Close table
			$HTMLMailBody .=  "</table>";
			$MailBody .=  "\n\nSee more at http://football.joshhughes.com/breakdown.php\n";
			$MailBody .= "\n\n\n Users may \"Opt Out\" of this reminder feature by changing their preferences using the \"Change Email Prefs\" link in the Log On Box.... \n This feature is turned on by default at user registration.";
			$HTMLMailBody .= "<BR>Don't forget to make your picks for the upcoming games for <B>Week $Weeknum</B>";
			
			//Write SQL Query to extract specified data
			$SQL = "SELECT * FROM NFLSchedule Where WEEK=".$Weeknum." ORDER BY GameDate, GameTime";
			//Open Record Set using SQL Query
			$result = mysql_query($SQL) or die("Cannot query the database.<br>" . mysql_error());
			$HTMLMailBody .= "<table bgcolor=#FFFFFF callpadding=\"5\" cellspacing=\"0\"><tr><TH colspan=2>Visitors</TH><TH>&nbsp;&nbsp;&nbsp;</TH><TH colspan=2>Home</TH><TH align=left width=100>Game Time</TH></tr>";
			
			$CurrentDate = 20031022;
			$row = -1;
			do{
			if (($myrow["Away"] != NULL) && ($myrow["Away"] != "")) {
			//increment i for the row color
			$row++;
				 if (($row%2) == 0) {  //if Even Row
					$HTMLMailBody .= "<tr bgcolor=\"FFFFFF\">";
				 }
				 else {//if Odd row
					$HTMLMailBody .= "<tr bgcolor=\"EEEEEE\">";
				 }
				 if ($myrow["GameDate"] == $CurrentDate) {
					//do nothing
				 } 
				 else {
				$CurrentDate = $myrow["GameDate"];
				$HTMLMailBody .= "<td colspan=\"6\"><B><U>".date('l F jS, Y',strtotime($myrow["GameDate"]))."</U></B></td></tr>";
				$row++;
				if (($row%2) == 0) {  //if Even Row
						 $HTMLMailBody .= "<tr bgcolor=\"FFFFFF\">";
				}
				else {//if Odd row
						 $HTMLMailBody .= "<tr bgcolor=\"EEEEEE\">";
				}
				 }//end if ($myrow["GameDate"] != $CurrentDate)
				 $HTMLMailBody .= "<td width=\"5\"><img src=\"http://football.joshhughes.com/images/small/".$myrow["Away"].".gif\"></td><td width=\"5\">".$myrow["Away"]."</td><td width=\"1\"> @ </td>";
				 $HTMLMailBody .= "<td width=\"5\">".$myrow["Home"]."</td><td width=\"5\"><img src=\"http://football.joshhughes.com/images/small/".$myrow["Home"].".gif\"></td>";
				 $HTMLMailBody .= "<td>".date('g:i A',strtotime($myrow["GameTime"]))." EST</td>";     
			}//end if (($myrow["Away"] != NULL) && ($myrow["Away"] != ""))
			}while($myrow = mysql_fetch_array($result));
			$HTMLMailBody .= "</table>";
			
			$HTMLMailBody .= "<BR><BR><BR><font size=1> Users may &quot;Opt Out&quot; of this weekly update feature by changing their preferences using the \"Change Email Prefs\" link in the Log On Box....<BR>This feature is turned on by default at user registration.</font>";
			
			$MailTo = $adminmail;
			//add From: header
			$headers = "From: Football@joshhughes.com\r\n";
			
			//specify MIME version 1.0
			$headers .= "MIME-Version: 1.0\r\n";
			
			//unique boundary
			$boundary = uniqid("HTMLDEMO");
			
			//tell e-mail client this e-mail contains//alternate versions
			$headers .= "Content-Type: multipart/alternative" ."; boundary = $boundary\r\n\r\n";
			
			//message to people with clients who don't
			//understand MIME
			$headers .= "This is a MIME encoded message.\r\n\r\n";
			
			//plain text version of message
			$headers .= "--$boundary\r\n" .
			 "Content-Type: text/plain; charset=ISO-8859-1\r\n" .
			 "Content-Transfer-Encoding: base64\r\n\r\n";
			$headers .= chunk_split(base64_encode($MailBody));
			
			//HTML version of message
			$headers .= "--$boundary\r\n" .
			 "Content-Type: text/html; charset=ISO-8859-1\r\n" .
			 "Content-Transfer-Encoding: base64\r\n\r\n";
			$headers .= chunk_split(base64_encode($HTMLMailBody));
			//Send an Email to me notifying me of a request
			//mail($MailTo, $MailSubject, "", $headers);  //message send
			mail($MailTo, $MailSubject, $MailBody, $MailFrom);  //message send
			echo "<H1>MailTo: $MailTo</H1>";
	}//end if($myrow = mysql_fetch_array($result))
	
	
	$MailTo = "<Football@joshhughes.com>";
	$MailFrom = "From: Football@joshhughes.com";
	$MailSubject = "Tuesday Email Script has been run";
	$MailBody = "The tuesdayemail.php script was run on ".date('l F jS, Y')." at ".date('g:i A',time() + (3600 * 3)).".";
	//Send an Email to me notifying me of a request
	mail($MailTo, $MailSubject, $MailBody, $MailFrom);  //message send
	echo "<H1>$MailBody</H1>";
	
?>
<SCRIPT language="JavaScript">
	//parent.location="http://football.joshhughes.com/dbupdate.php?update=ranks";
</SCRIPT>
</body>
</html>